import axios from "axios";
import { PromiseEx } from "../utils";

/**
 * 文件上传类
 */
export const uploader = (server, file, bucket, meta)=>
{
    var uploaded = 0;               // 已上传的大小
    var slice_size = 512 * 1024,    // 分片大小: 512kb
        headers = { "Content-Type": "multipart/form-data" };

    if(file.size <= slice_size) {
        let params = new FormData();
        params.append('file', file)
        params.append('bucket', bucket);
        if(null !== meta && undefined !== meta){
            params.append('meta',meta);
        }
        return new PromiseEx((resolve, reject, update,cancel)=>{
            axios.post(server + '/http/one', params,{
                headers,
                onUploadProgress:(e)=>{
                    e.percent = Math.floor(100 * (e.loaded / e.total));
                    update(e);
                }
            }).then(e=>resolve(e)).catch(e=>reject(e))
        });
    }

    return new PromiseEx(async (resolve, reject, update, cancel)=>{
        var total_size = file.size, index = 0;
        var name, res;
        while(uploaded < total_size){
            var params = new FormData();
            if(uploaded == 0){
                params.append('bucket',bucket);
                params.append('size', file.size);
                params.append('type', file.type);
            }else{
                params.append('type', file.type);
                params.append('name', name);
            }
            var size = Math.min(slice_size, total_size - uploaded);
            var f = file.slice(uploaded, uploaded + size);
            params.append('file', f);

            // 最后一个包 带上 meta 参数
            if(size + uploaded == total_size){
                if(undefined !== meta && null !==  meta){
                    params.append('meta', JSON.stringify(meta));
                }
            }
            
            res = await axios.post(server + '/http/slicesave', params,{
                headers,
                onUploadProgress:(e)=>{
                    e.loaded =Math.min(uploaded + e.loaded, total_size), e.total = total_size;
                    e.percent = Math.floor(100 * (e.loaded / e.total));
                    update(e);
                },
            });

            if(res.data.success) {

                //后期照片上传服务器将加入多进程支持.
                if(index == 0 && res.data.hasOwnProperty('sid')){
                    headers['X-Sid'] = res.data.sid;
                }

                uploaded += size;
                name = res.data.file ?? name;
            }else{
                reject(res.data.message);
                return;
            }
            index ++;
            //console.log('upload', total_size, uploaded);
        }
        res.data.file = name
        resolve(res);
    })
}
